﻿using System;
using System.Collections.Generic;
using System.IO;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Util;

namespace Top.Api.Sync
{
    public class TopApiService
    {
        private const long DEFAULT_PAGE_SIZE = 100L;
        private const long DEFAULT_WAIT_TIME = 100L;

        private ITopClient client;

        public TopApiService(ITopClient client)
        {
            this.client = client;
        }

        public void SyncSoldTrades(DateTime start, DateTime end, string sessionKey)
        {
            TradesSoldGetRequest req = new TradesSoldGetRequest();
            req.Fields = "tid";
            req.Type = "ec,fixed,auction,auto_delivery,cod,independent_shop_trade,independent_simple_trade,shopex_trade,netcn_trade,external_trade,hotel_trade,fenxiao,game_equipment,instant_trade,b2c_cod,super_market_trade,super_market_cod_trade,alipay_movie,taohua,waimai,nopaid";
            req.StartCreated = start;
            req.EndCreated = end;
            req.PageSize = DEFAULT_PAGE_SIZE;
            req.UseHasNext = true;

            long pageNo = 1L;
            TradesSoldGetResponse rsp = null;
            do
            {
                req.PageNo = pageNo;
                rsp = client.Execute(req, sessionKey);
                if (!rsp.IsError && rsp.Trades != null)
                {
                    Console.WriteLine("同步中>>>第" + req.PageNo + "页");
                    foreach (Trade trade in rsp.Trades)
                    {
                        GetTradeFullInfo(trade.Tid, sessionKey); // FIXME 保存订单到数据库中
                    }
                    pageNo++;
                }
            } while (rsp != null && (rsp.IsError || rsp.HasNext));
        }

        public void SyncIncrementSoldTrades(DateTime start, DateTime end, string sessionKey)
        {
            TradesSoldIncrementGetRequest req = new TradesSoldIncrementGetRequest();
            req.Fields = "tid";
            req.Type = "ec,fixed,auction,auto_delivery,cod,independent_shop_trade,independent_simple_trade,shopex_trade,netcn_trade,external_trade,hotel_trade,fenxiao,game_equipment,instant_trade,b2c_cod,super_market_trade,super_market_cod_trade,alipay_movie,taohua,waimai,nopaid";
            req.StartModified = start;
            req.EndModified = end;
            req.PageSize = DEFAULT_PAGE_SIZE;
            req.UseHasNext = false;

            TradesSoldIncrementGetResponse rsp = client.Execute(req, sessionKey);
            if (!rsp.IsError)
            {
                long pageCount = ((rsp.TotalResults + req.PageSize - 1) / req.PageSize).Value;
                while (pageCount > 0)
                {
                    req.PageNo = pageCount;
                    req.UseHasNext = true;
                    rsp = client.Execute(req, sessionKey);
                    if (!rsp.IsError)
                    {
                        Console.WriteLine("同步中>>>第" + req.PageNo + "页");
                        foreach (Trade trade in rsp.Trades)
                        {
                            GetTradeFullInfo(trade.Tid, sessionKey); // FIXME 保存订单到数据库中
                        }
                        pageCount--;
                    }
                }
            }
        }

        public Trade GetTradeFullInfo(long tid, String sessionKey)
        {
            TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
            req.Fields = "tid,seller_nick,buyer_nick,buyer_message,orders"; // FIXME 增加应用需要的字段
            req.Tid = tid;
            TradeFullinfoGetResponse rsp = client.Execute(req, sessionKey);
            if (!rsp.IsError)
            {
                Console.WriteLine("查询订单详情成功：" + rsp.Body);
                return rsp.Trade;
            }
            return null;
        }

        public Nullable<long> AsyncSoldTrades(string start, string end, string sessionKey)
        {
            TopatsTradesSoldGetRequest req = new TopatsTradesSoldGetRequest();
            req.Fields = "tid,seller_nick,buyer_nick,buyer_message,orders";
            req.StartTime = start;
            req.EndTime = end;
            TopatsTradesSoldGetResponse rsp = client.Execute(req, sessionKey);
            if (!rsp.IsError)
            {
                return rsp.Task.TaskId;
            }
            return null;
        }

        public string GetTaskResultUrl(long taskId)
        {
            TopatsResultGetRequest req = new TopatsResultGetRequest();
            req.TaskId = taskId;
            TopatsResultGetResponse rsp = client.Execute(req);
            if (!rsp.IsError)
            {
                if ("done".Equals(rsp.Task.Status))
                {
                    return rsp.Task.DownloadUrl;
                }
            }
            return null;
        }

        public void PermitUser(string sessionKey)
        {
            IncrementCustomerPermitRequest req = new IncrementCustomerPermitRequest();
            req.Type = "notify";
            client.Execute(req, sessionKey);
        }

        public void DownloadAndProcess(string url)
        {
            string zipFile = AtsUtils.Download(url, "e:/Downloads/Trade/Zip");
            List<string> files = AtsUtils.Unzip(zipFile, "e:/Downloads/Trade/Unzip");
            foreach (string file in files)
            {
                using (StreamReader reader = new StreamReader(file))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        TradeFullinfoGetResponse rsp = TopUtils.ParseResponse<TradeFullinfoGetResponse>(line);
                        Trade trade = rsp.Trade; // FIXME 保存订单到数据库中
                        Console.WriteLine("处理订单：" + trade.Tid);
                    }
                }
            }
        }
    }
}
